import { userlogin, userlogout } from '@/api/api'

let userInfo = window.sessionStorage.getItem('userInfo')
let account = '', authority = [], id = '', isAdmin = 0, supperAdmin = false, remark = '', username = '', valid = 1
if (typeof userInfo == 'string' && userInfo.length > 1) {
  userInfo = JSON.parse(userInfo)
  account = userInfo.account
  authority = userInfo.authority
  id = userInfo.id
  isAdmin = userInfo.isAdmin
  supperAdmin = userInfo.supperAdmin
  remark = userInfo.remark
  username = userInfo.username
  valid = userInfo.valid
}
const user = {
  state: {
    account,
    authority,
    id,
    isAdmin,
    supperAdmin,
    remark,
    username,
    valid,

    avatar: '',
  },

  mutations: {
    SET_USERINFO: (state, userInfo) => {
      state.account = userInfo.account
      state.authority = userInfo.authority
      state.id = userInfo.id
      state.isAdmin = userInfo.isAdmin
      state.supperAdmin = userInfo.supperAdmin
      state.remark = userInfo.remark
      state.username = userInfo.username
      state.valid = userInfo.valid
      window.sessionStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      console.error('login')
      const username = userInfo.account.trim()
      return new Promise((resolve, reject) => {
        console.log('run login')
        userlogin(username, userInfo.password).then(response => {
          const data = response.data
          console.log(response)
          commit('SET_USERINFO', data)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      console.log('logout')
      return new Promise((resolve, reject) => {
        commit('SET_USERINFO', {
          account: "",
          authority: [],
          id: null,
          isAdmin: 0,
          supperAdmin: false,
          remark: "",
          username: "",
          valid: 1,
        })
        commit('SET_HASSETROUTER_FALSE')
        userlogout()
        resolve()
      })
    }
  }
}

export default user
